<template>
  <div class="page-miH page-bgBack">
    <div class="buttonBox">
      <a-button type="primary" @click="goAdd"> <a-icon type="plus" />新增工资表模板 </a-button>
      <a-button v-if="isContainByString('contractAdmin')" type="primary" @click="showIssueModa"> 下发工资表模板 </a-button>
    </div>
    <div class="tableBox">
      <a-table :columns="columns" :pagination="false" row-key="id" :loading="loading" :data-source="data">
        <a slot="action" slot-scope="text, record" class="edit" style="margin-left: -10px">
          <span @click="goEdit(record)">编辑</span>
          <a-divider type="vertical" />
          <span>
            <a-popconfirm :title="'确定删除' + record.name + '?'" @confirm="deleteSalaryTemplatesList(record)">
              <a-icon slot="icon" type="question-circle-o" style="color: red" />
              <a href="#" :disabled="record.name === '默认模板' || record.name === '计时制模板'">删除</a>
            </a-popconfirm>
          </span>
        </a>
      </a-table>
    </div>
    <a-modal
      :visible="issueModalVisible"
      title="下发工资模板"
      width="538px"
      :destroy-on-close="true"
      @ok="confirmIssueModal"
      @cancel="handleCancelIssueModal"
    >
      <a-row>
        <a-col :span="12">
          <span>请选择工资模板</span>
          <a-select
            v-model="contractList"
            mode="multiple"
            placeholder="请选择工资模板"
            option-filter-prop="children"
            show-search
            :filter-option="filterOption"
            style="width: 240px; margin-top: 10px"
          >
            <a-select-option v-for="(item, index) in contractData" :key="index" :value="item.id">
              <a-tooltip placement="left" :title="item.name">
                {{ item.name }}
              </a-tooltip>
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :span="12">
          <span>请选择下发用工单位</span>
          <a-tree-select
            :value="companyList"
            :treeData="dataList"
            :filterTreeNode="false"
            treeCheckable
            placeholder="请选择用工单位"
            style="width: 240px; margin-top: 10px; max-height: 350px; overflow: auto"
            @search="treeSearch"
            @change="companySelectChange"
          />
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>
<script>
import { getTemplates, deleteSalaryTemplates, deleteSalary, batchDeleteSalary } from "@/api/wages/template";
import { findCompanyGroup } from "@/api/company/contract";
import { getNotArchiveById } from "@/api/wages/monthly";
import { isContainByString } from "@/utils/index";
import { saveIssuedSeal } from "./api";
import { formatCompanyTree } from "@/utils/tools";
export default {
  data() {
    return {
      isContainByString,
      loading: true,
      columns: [],
      data: [],
      dataList: [],
      companyId: this.$store.state.hr.companyId,
      // modal显示隐藏
      issueModalVisible: false,
      // 下发选择框合同数据
      contractData: [],
      // 已选的合同模板数据
      contractList: [],
      // 已选的公司数据
      companyList: []
    };
  },
  created() {
    this.findCompanyGroup();
    this.getTemplatesList();
    if (this.isContainByString("contractAdmin")) {
      this.columns = [
        {
          title: "模板名称",
          dataIndex: "name",
          key: "name"
        },
        {
          title: "工资项",
          dataIndex: "salaryTemplateItem",
          key: "salaryTemplateItem",
          scopedSlots: { customRender: "salaryTemplateItem" }
        },

        {
          title: "操作",
          key: "action",
          scopedSlots: { customRender: "action" }
        }
      ];
    } else {
      this.columns = [
        {
          title: "模板名称",
          dataIndex: "name",
          key: "name"
        },
        {
          title: "工资项",
          dataIndex: "salaryTemplateItem",
          key: "salaryTemplateItem",
          scopedSlots: { customRender: "salaryTemplateItem" }
        },
        {
          title: "适用薪资组",
          dataIndex: "salaryGroup",
          key: "salaryGroup",
          scopedSlots: { customRender: "salaryGroup" }
        },
        {
          title: "操作",
          key: "action",
          scopedSlots: { customRender: "action" }
        }
      ];
    }
  },
  methods: {
    companySelectChange(companyKeys) {
      this.companyList = companyKeys.filter((item) => item.includes("_company_"));
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    treeSearch(e) {
      this.findCompanyGroup(e);
    },
    findCompanyGroup(e) {
      findCompanyGroup({ name: e || null })
        .then((res) => {
          this.dataList = formatCompanyTree(res.data);
          this.companyList = JSON.parse(JSON.stringify(this.companyList));
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    deleteSalaryTemplatesList(record) {
      getNotArchiveById({ salaryTemplateId: record.id }).then((res) => {
        // res.data.monthly
        if (res.data) {
          var arr = [];
          res.data.forEach((item, index) => {
            arr.push(item.monthly);
          });
          arr = arr.join(",");
          var idList = [];
          res.data.forEach((item, index) => {
            idList.push(item.id);
          });
          const _this = this;
          this.$confirm({
            okText: "确定",
            cancelText: "取消",
            title: `该模板已在${arr}月创建月工资表，删除模板会同时删除未归档的月工资表，仍旧继续吗？`,
            onOk() {
              deleteSalaryTemplates(record.id).then(({ success }) => {
                if (success) {
                  _this.$notification["success"]({ message: "删除成功" });
                  _this.getTemplatesList();
                }
              });
              batchDeleteSalary(idList).then(({ success }) => {});
              // deleteSalary(res.data.id).then(({ success }) => {});
            }
          });
        } else {
          deleteSalaryTemplates(record.id).then(({ success }) => {
            if (success) {
              this.$notification["success"]({ message: "删除成功" });
              this.getTemplatesList();
            }
          });
        }
      });
    },
    getTemplatesList() {
      this.loading = true;
      getTemplates({
        companyId: this.isContainByString("contractAdmin") ? "0" : this.companyId
      }).then((res) => {
        this.loading = false;
        this.data = res.data;
        this.contractData = res.data;
        for (var i = 0; i < res.data.length; i++) {
          this.data[i].salaryTemplateItem = [];
          this.data[i].salaryGroup = [];
          if (res.data[i].salaryTemplateItemVOList && res.data[i].salaryTemplateItemVOList.length) {
            for (var p = 0; p < res.data[i].salaryTemplateItemVOList.length; p++) {
              if (res.data[i].salaryTemplateItemVOList[p].isUse === true) {
                this.data[i].salaryTemplateItem.push(res.data[i].salaryTemplateItemVOList[p].name + " ");
              }
            }
          }

          if (res.data[i].salaryGroupVOList && res.data[i].salaryGroupVOList.length) {
            for (var s = 0; s < res.data[i].salaryGroupVOList.length; s++) {
              this.data[i].salaryGroup.push(res.data[i].salaryGroupVOList[s].name);
            }
          }
        }
      });
    },
    // 跳转到新增工资条模板
    goAdd() {
      this.$router.push({
        path: `/${this.isContainByString("contractAdmin") ? "contractAdmin" : "wages"}/template/add`
      });
    },
    goEdit(record) {
      this.$router.push({
        path: `/${this.isContainByString("contractAdmin") ? "contractAdmin" : "wages"}/template/edit`,
        query: {
          id: record.id
        }
      });
    },
    saveIssuedSeal() {
      if (this.companyList.length === 0) {
        this.$notification["error"]({
          message: "错误",
          description: "请选择需要下发的公司"
        });
        return;
      }
      if (this.contractList.length === 0) {
        this.$notification["error"]({
          message: "错误",
          description: "请选择需要下发的合同模板"
        });
        return;
      }
      const companyArr = Array.from(new Set(this.companyList.map((item) => item.split("_")[2])));
      const data = {
        companyId: companyArr,
        salaryTemplateIds: this.contractList
      };
      saveIssuedSeal(data)
        .then((res) => {
          this.issueModalVisible = false;
          this.$notification["success"]({
            message: "成功",
            description: "下发成功"
          });
          this.companyList = [];
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    // 方法
    confirmIssueModal() {
      // TODO 下发接口
      this.saveIssuedSeal();
    },
    handleCancelIssueModal() {
      this.issueModalVisible = false;
      // 已选的合同模板数据
      this.contractList = [];
      // 已选的公司数据
      this.companyList = [];
    },
    showIssueModa() {
      this.issueModalVisible = true;
    }
  }
};
</script>
<style lang="scss" scoped>
.buttonBox {
  padding-top: 25px;
  margin-left: 20px;
  display: flex;
  justify-content: space-between;
  margin-right: 20px;
}
.tableBox {
  padding: 18px;
}
.edit {
  color: var(--primary);
}
</style>
